from random import randint
import logging
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django_redis import get_redis_connection
from apps.verifications import constants
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger("django")


class SMSCodeView(APIView):
    """短信验证码"""

    def get(self, request, mobile):
        """
        1、生成随机验证码
        2、创建redis链接对象存验证码
        3、利用荣联云通信发送短信验证码
        4、响应
        :param request:
        :param mobile:
        :return:
        """
        # 先从redis获取发送验证码标记
        redis_conn = get_redis_connection("verify_codes")
        send_flag = redis_conn.get(f"send_flag_{mobile}")  # 取值不会放到管道中
        if send_flag:  # 如果取到标记，则是频繁发短信
            return Response(
                {"message": "手机号频繁发送短信验证码"}, status=status.HTTP_400_BAD_REQUEST
            )
        sms_code = "%06d" % randint(0, 999999)
        logger.info(f"mobile:{mobile}_msm_code:{sms_code}")

        pl = redis_conn.pipeline()  # 创建redis管道

        pl.setex(
            f"sms_{mobile}", constants.SMS_CODE_REDIS_EXPIRES, sms_code
        )  # 存储验证码 key,过期时间,值
        pl.setex(f"send_flag_{mobile}", constants.SMS_CODE_REDIS_EXPIRES, 1)
        pl.execute()  # 执行管道
        send_sms_code.delay(
            mobile, sms_code
        )  # 耗时任务需要使用异步处理,异步函数不能直接使用"函数名()执行"需要使用函数名.delay(参数1,参数2)
        return Response(data={"message": "ok"}, status=status.HTTP_200_OK)
